#include <QToolButton>
#include <QLabel>
#include <QToolBar>
#include <QAction>
#include <QListWidget>
#include <QVBoxLayout>
#include <QInputDialog>
#include <QUrl>
#include <QScrollBar>

#include "downloadcenter.h"
#include "downloaditem.h"
#include "downloaditemlist.h"

namespace Jcr
{

class DownloadCenterPrivate
{
public:
    QAction* clearAllAct;
    QAction* clearFinishedAct;
    QAction* addAct;
    Jcr::DownloadItemList* itemListWidget;
};

DownloadCenter::DownloadCenter(QWidget *parent) : QWidget(parent)
{
    d_ptr = new DownloadCenterPrivate;
    init();
}

DownloadCenter::~DownloadCenter()
{
    delete d_ptr;
}

void DownloadCenter::download(const QUrl &url)
{
    Jcr::DownloadItem* di = new Jcr::DownloadItem();
    di->setUrl(QUrl(url));
    di->setSaveDir("F:/");
    d_ptr->itemListWidget->addItem(di);
    di->start();
}

void DownloadCenter::download(const QUrl &url, const QString& saveName, const QString& saveDir)
{
    Jcr::DownloadItem* di = new Jcr::DownloadItem();
    di->setUrl(url);
    di->setSaveDir(saveDir);
    di->setSaveName(saveName);
    d_ptr->itemListWidget->addItem(di);
    di->start();
}

void DownloadCenter::addUrl()
{
    QString url = QInputDialog::getText(this, tr("Add download item"), tr("Url:"));
    if (!url.isEmpty()) {
        Jcr::DownloadItem* di = new Jcr::DownloadItem();
        di->setUrl(QUrl(url));
        di->setSaveDir("G:/");
        d_ptr->itemListWidget->addItem(di);
        di->start();
    }
}

void DownloadCenter::clearFinished()
{
    auto items = d_ptr->itemListWidget->items();
    foreach (auto item, items) {
        if (item->isFinished())
            d_ptr->itemListWidget->removeItem(item);
    }
}

void DownloadCenter::clearAll()
{
    d_ptr->itemListWidget->clear();
}

void DownloadCenter::init()
{
    setMinimumWidth(250);
    QVBoxLayout* mainLayout = new QVBoxLayout;

    QToolBar* toolbar = new QToolBar(tr("Download Center"), this);
    d_ptr->clearAllAct = new QAction(tr("Clear All"), this);
    toolbar->addAction(d_ptr->clearAllAct);
    d_ptr->clearFinishedAct = new QAction(tr("Clear Finished"), this);
    toolbar->addAction(d_ptr->clearFinishedAct);
    d_ptr->addAct = new QAction(tr("Add Download"), this);
    toolbar->addAction(d_ptr->addAct);
    mainLayout->addWidget(toolbar);

    d_ptr->itemListWidget = new Jcr::DownloadItemList(this);
    mainLayout->addWidget(d_ptr->itemListWidget);

    setLayout(mainLayout);

    connect(d_ptr->clearAllAct, SIGNAL(triggered()), this, SLOT(clearAll()));
    connect(d_ptr->clearFinishedAct, SIGNAL(triggered()), this, SLOT(clearFinished()));
    connect(d_ptr->addAct, SIGNAL(triggered()), this, SLOT(addUrl()));

    setWindowTitle(tr("Download Center"));
}

} // namespace jcr
